package ie.lawlor.amvc.component.tab.swing;

import ie.lawlor.amvc.IView;
import ie.lawlor.amvc.swing.JTabbedPaneView;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * @author blawlor
 *
 */
public class TabView extends JTabbedPaneView {
  
  private Map panels= new HashMap(); 
  private List keys = new ArrayList();
  private int selectedIndex = -1;
  
  public TabView(String name) {
    super(name);
    addChangeListener(new ChangeListener(){
      public void stateChanged(ChangeEvent e){
        if (selectedIndex != getSelectedIndex()){
          selectedIndex = getSelectedIndex();
          tabSelected();
        }
      }
    });
  }
  
  public void setViews(List tabNames){
    for (ListIterator itr = tabNames.listIterator(); itr.hasNext();){
      String tabName = (String)itr.next();
      JPanel panel = new JPanel(new BorderLayout());
      panels.put(tabName, panel);
      keys.add(tabName);
      add(tabName, panel);
    }
  }
  
  public List getViews(){
    //TODO How do we order this? We need an ordered map!
    return new ArrayList(panels.keySet());
  }
  public Container getContainer(String viewName) {
    return (Container)panels.get(viewName);
  }
  
  private void tabSelected(){
    System.out.println("*******TabSelected");
    String selectedView = (String)keys.get(getSelectedIndex());
    Container selectedContainer = getContainer(selectedView);
    Component[] children = selectedContainer.getComponents();
    for (int i = 0; i < children.length; ++i){
      ((IView)children[i]).setViewVisible(true);
    }
//    fire(new Event(getController().getEvent(TabController.PAGE_CHANGED), 
//            this, 
//            new Integer(getSelectedIndex())));
  }
  
}
